import base64

import pickle

from django_redis import get_redis_connection


def merge_cookie_redis(request,response,user):
    # 先检查cookie如果没有直接返回
    cookie = request.COOKIES.get('cart')
    if not cookie:
        return response
    cookie = cookie.encode()
    # 返回的是b'asdfghjklv
    cookie = base64.b64decode(cookie)
    # 此时返回的是b'/xx0/xx1/xx2
    ret_dict = pickle.loads(cookie)
    '''{sku_id:{'count':count
                'selected':selected}}'''
    '''user_id:{sku_id:count}
        select_user_id:{sku_id}'''
    # 遍历cookie
    user_id=user.id
    redis_connect = get_redis_connection('cart')
    for sku_id,count_selected in ret_dict.items(): # items
        print(sku_id,count_selected) # 16 {'selected': True, 'count': 1}
        '''hset(name, key, value)'''
        ''''cart_%s' % user_id,sku_id,amount=count'''
        redis_connect.hset('cart_%s' % user_id,sku_id,count_selected['count'])
        if count_selected['selected']:
            '''sadd(name, *values)'''
            ''''cart_selected_%s' % user_id,selected'''
            redis_connect.sadd('cart_selected_%s' % user_id,count_selected['selected'])
        else:
            '''srem(name, *values)'''
            redis_connect.srem('cart_selected_%s' % user_id,count_selected['selected'])

    # 删除cookie
    response.delete_cookie('cart')
    return response